import { showMessage } from '@/components/antd-comp/message'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import { Button, Input, Modal } from 'antd'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { EnterpriseAdd, EnterpriseEdit } from '../API'
import './style/index.less'

const FirmEditDia = ({ open, setOpen, obj, submitData }) => {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  // ------埋点------
  const { FirmBuriedEvent } = useBuriedEvent()
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  /* dialog内容 */
  const [person, setPerson] = useState({
    name: '',
    code: '',
    id: ''
  })
  const { t } = useTranslation()
  // State for errors
  const [errors, setErrors] = useState<any>({})
  useEffect(() => {
    setPerson({
      ...person,
      ...obj
    })
  }, [])
  /* 提示报信信息 */
  const [error, setError] = useState({ name: false, code: false })

  const close = () => {
    setOpen(false)
    submitData()
  }
  /* 提交表单 */
  const handleCreate = () => {
    const isValid = validateForm()
    if (isValid) {
      const obj = {
        ...person
      }
      const buriedInfo = {
        page: obj.id ? '编辑企业管理弹窗' : '创建企业管理弹窗',
        event_name: '【确定】按钮',
        data_id: obj.id
      }
      console.log('12312132', obj)
      if (obj.id) {
        EnterpriseEdit({
          ...obj
        })
          .then((res: any) => {
            FirmBuriedEvent({ ...buriedInfo })
            close()
            showMessage({
              content: '修改成功',
              type: 'success'
            })
          })
          .catch(() => {
            FirmBuriedEvent({ ...buriedInfo })
          })
      } else {
        EnterpriseAdd({
          ...obj
        })
          .then((res: any) => {
            FirmBuriedEvent({ ...buriedInfo })
            close()
            showMessage({
              content: '新增成功',
              type: 'success'
            })
          })
          .catch(() => {
            FirmBuriedEvent({ ...buriedInfo })
          })
      }
    }
  }
  // Validate form fields
  const validateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return '企业名称不可为空'
        if (value.length > 50) return '最多50个字符'
        return ''
      case 'code':
        if (!value) return 'code不可为空'
        return ''
      default:
        return ''
    }
  }
  // Handle field change
  const handleChange = (e, type) => {
    const error = validateField(type, e)
    setErrors(prev => ({ ...prev, [type]: error }))
    if (type === 'name') {
      setPerson({ ...person, name: e })
    } else if (type === 'code') {
      setPerson({ ...person, code: e })
    }
  }
  // Validate entire form
  const validateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(person).forEach(key => {
      const error = validateField(key, person[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }
  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case max-h-[40%]"
        title={person.id ? '编辑' : '新增'}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button
            key="cancel"
            className="closeBtnStyles closeBtnWid"
            shape="round"
            onClick={() => {
              FirmBuriedEvent({
                page: person.id ? '编辑企业管理弹窗' : '创建企业管理弹窗',
                event_name: '【取消】按钮'
              })
              setOpen(false)
            }}
          >
            {t('cancel')}
          </Button>,
          <ThemeBtn key="create" className="closeBtnWid" onClick={() => handleCreate()}>
            确认
          </ThemeBtn>
        ]}
      >
        <div
          style={{ overflowY: 'scroll', height: '330px' }}
          className="caseOverFlowY flex flex-col gap-4 py-2 pr-1 sm:max-w-[825px]"
        >
          {/* 企业名 */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              企业名称
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              name="name"
              autoComplete="off"
              value={person.name}
              onChange={e => handleChange(e.target.value, 'name')}
              placeholder="企业名称"
              className={`col-span-3 ${error.name && 'border-red-400'} contMarginTop inoutHig`}
            />
            {errors.name && <p className="bisheng-tip mt-1">{errors.name}</p>}
          </div>
          {/* code */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              code
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              name="code"
              disabled={!!(person.id && person.code)}
              autoComplete="off"
              value={person.code}
              onChange={e => {
                const numericValue = e.target.value.replace(/[^0-9]/g, '')
                handleChange(numericValue, 'code')
              }}
              placeholder="code"
              className={`col-span-3 ${error.name && 'border-red-400'} contMarginTop inoutHig`}
            />
            {errors.code && <p className="bisheng-tip mt-1">{errors.code}</p>}
          </div>
        </div>
      </Modal>
    </>
  )
}

export default FirmEditDia
